package front_comment_api

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/res"
	"blog_go/utils"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type CommentAddReq struct {
	ArticleID       uint   `json:"article_id" binding:"required"`
	Content         string `json:"content" binding:"required"`
	ParentCommentID *uint  `json:"parent_comment_id"`
}

func (CommentApi) CommentAdd(c *gin.Context) {
	var req CommentAddReq
	if err := c.ShouldBindJSON(&req); err != nil {
		logrus.Error(err)
		panic(err)
	}
	_claims := c.MustGet(utils.Claims)
	claims := _claims.(utils.CustomClaims)
	// 查询文章
	var article models.ArticleModel
	err := global.DB.First(&article, req.ArticleID).Error
	if err != nil {
		logrus.Error(err)
		panic(err)
	}
	if req.ParentCommentID != nil {
		// 是子评论
		var parentComment models.CommentModel
		err := global.DB.First(&parentComment, *req.ParentCommentID).Error
		if err != nil {
			logrus.Error(err)
			panic(err)
		}
		err = global.DB.Transaction(func(tx *gorm.DB) error {
			// 修改文章评论数
			if err := tx.Exec("update article set comment_count = comment_count + 1 where id = ?", article.ID).Error; err != nil {
				return err
			}
			// 修改父评论的评论数
			if err := tx.Exec("update comment set comment_count = comment_count + 1 where id = ?", parentComment.ID).Error; err != nil {
				return err
			}
			// 添加评论
			comment := models.CommentModel{
				ParentCommentID: req.ParentCommentID,
				Content:         req.Content,
				DiggCount:       0,
				CommentCount:    0,
				ArticleID:       req.ArticleID,
				UserID:          claims.UserID,
			}
			if err := tx.Create(&comment).Error; err != nil {
				return err
			}
			return nil
		})
		if err != nil {
			logrus.Error(err)
			panic(err)
		}
		res.OkWithMessage("评论成功", c)
		return
	}
	// 根评论
	global.DB.Create(&models.CommentModel{
		ParentCommentID: req.ParentCommentID,
		Content:         req.Content,
		DiggCount:       0,
		CommentCount:    0,
		ArticleID:       req.ArticleID,
		UserID:          claims.UserID,
	})
	res.OkWithMessage("评论成功", c)
}
